package com.padakeji.android.pworks.module.image.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;

import com.padakeji.android.pworks.R;
import com.padakeji.android.pworks.app.PadaActivity;
import com.padakeji.android.pworks.content.PadaResourceHelper;
import com.padakeji.android.pworks.module.image.common.ImageCaptureHelper;
import com.padakeji.android.pworks.module.image.common.ImageInfoUtil;
import com.padakeji.android.pworks.module.image.entity.ImageDirectory;
import com.padakeji.android.pworks.module.image.entity.ImageInfo;
import com.padakeji.android.pworks.module.image.present.ImagePickerPresent;
import com.padakeji.android.pworks.ui.UIHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AtanL on 2015/9/14.
 */
public class ImagePickerActivity extends PadaActivity implements ImagePickerView {

    private static ThreadLocal<ArrayList<ImageInfo>> selectedImagesLocal = new ThreadLocal<>();

    public static ArrayList<ImageInfo> getSelectedImages() {
        ArrayList<ImageInfo> imageInfos = selectedImagesLocal.get();
        if (imageInfos == null) {
            imageInfos = new ArrayList<>();
            selectedImagesLocal.set(imageInfos);
        }
        return imageInfos;
    }

    public final static String RESULT_DATA = "RESULT_DATA";
    public final static int REQUEST_CODE_IMAGE_CAPTURE = 1011;

    private ImagePickerPresent p;
    private UIHelper uiHelper;
    private ImageCaptureHelper imageCaptureHelper;

    private ImageView backImage;
    private Button finishBtn;

    private RecyclerView imagesRecycler;
    private List<ImageDirectory> imageDirectories = new ArrayList<>();;
    private ImageGridAdapter imageGridAdapter;

    private Button switchDirBtn;
    private Button previewBtn;

    private ListPopupWindow switchDirPanel;
    private DirectoryListAdapter directoryListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pworks_activity_image_picker);

        uiHelper = new UIHelper(this);
        imageCaptureHelper = new ImageCaptureHelper();
        p = new ImagePickerPresent(this, this);

        findViews();
        initViews();

        p.loadImages();
    }

    private void findViews() {
        backImage = (ImageView) findViewById(R.id.pworks_activity_image_picker_image_back);
        finishBtn = (Button) findViewById(R.id.pworks_activity_image_picker_btn_finish);
        imagesRecycler = (RecyclerView) findViewById(R.id.pworks_activity_image_picker_recycler_images);
        switchDirBtn = (Button) findViewById(R.id.pworks_activity_iamge_picker_btn_switch_directory);
        previewBtn = (Button) findViewById(R.id.pworks_activity_image_picker_btn_preview);
    }

    private void initViews() {
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ImageInfo> selectedImages = imageGridAdapter.getSelectedImages();
                if (selectedImages.size() > 0) {
                    Intent i = new Intent();
                    i.putStringArrayListExtra(RESULT_DATA, ImageInfoUtil.toPathArray(selectedImages));
                    setResult(RESULT_OK, i);
                    finish();
                }
            }
        });
        imageGridAdapter = new ImageGridAdapter(this, imageDirectories);
        imageGridAdapter.setOnItemCheckListener(new ImageGridAdapter.OnItemCheckListener() {
            @Override
            public void onItemCheck(int directoryIndex, int positionInDirectory) {
                boolean b = imageGridAdapter.getSelectedImages().size() > 0;
                finishBtn.setClickable(b);
            }
        });
        imageGridAdapter.setOnCameraClickListener(new ImageGridAdapter.OnCameraClickListener() {
            @Override
            public void onCameraClick() {
                takePhoto();
            }
        });
        imagesRecycler.setAdapter(imageGridAdapter);
        GridLayoutManager mLayoutManager = new GridLayoutManager(this, 3);
        imagesRecycler.setLayoutManager(mLayoutManager);

        directoryListAdapter = new DirectoryListAdapter(this, imageDirectories);
        switchDirBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleSwitchDirPanel();
            }
        });
        previewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                previewImages();
            }
        });
    }

    private void takePhoto() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePhotoIntent = imageCaptureHelper.newImageCaptureIntent();
            if (takePhotoIntent == null) {
                return;
            }
            startActivityForResult(takePhotoIntent, REQUEST_CODE_IMAGE_CAPTURE);
        } else {
            uiHelper.showToast("请确认已经插入SD卡");
        }
    }

    private void previewImages() {
        if (imageGridAdapter.getSelectedImages().size() > 0) {
            Intent i = new Intent(this, ImagePreviewActivity.class);
            int currentImageIndex = 0;
            i.putExtra(ImagePreviewActivity.EXTRA_CURRENT_IMAGE_INDEX, currentImageIndex);
            i.putExtra(ImagePreviewActivity.EXTRA_IMAGE_INFOS, imageGridAdapter.getSelectedImages());
            startActivity(i);
        } else {
            uiHelper.showToast("请先选择需要预览的图片");
        }
    }

    private void toggleSwitchDirPanel() {
        if (switchDirPanel == null) {
            switchDirPanel = new ListPopupWindow(this);
            switchDirPanel.setAnchorView(switchDirBtn);
            switchDirPanel.setAdapter(directoryListAdapter);
            switchDirPanel.setWidth(ListPopupWindow.MATCH_PARENT);
            switchDirPanel.setHeight(Math.round(new PadaResourceHelper(this).getDimen(R.dimen.pworks_activity_image_picker_directory_popup)));
            switchDirPanel.setModal(true);
            switchDirPanel.setDropDownGravity(Gravity.BOTTOM);
            switchDirPanel.setAnimationStyle(R.style.Animation_AppCompat_DropDownUp);
            switchDirPanel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switchDirPanel.dismiss();
                    ImageDirectory d = directoryListAdapter.getItem(position);
                    switchDirBtn.setText(d.name);
                    imageGridAdapter.setCurrentDirectoryIndex(position);
                    imageGridAdapter.notifyDataSetChanged();
                }
            });
        }

        if (switchDirPanel.isShowing()) {
            switchDirPanel.dismiss();
        } else {
            switchDirPanel.show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                uiHelper.showToast("" + imageCaptureHelper.getCapturedImagePath());
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        imageGridAdapter.notifyDataSetChanged();
    }

    @Override
    public void finish() {
        selectedImagesLocal.remove();
        super.finish();
    }

    @Override
    public void showImages(List<ImageDirectory> imageDirectories) {
        this.imageDirectories.clear();
        this.imageDirectories.addAll(imageDirectories);
        imageGridAdapter.notifyDataSetChanged();
        directoryListAdapter.notifyDataSetChanged();
    }
}
